﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;

namespace MxWeiXinPF.Common
{
   public class PicBase64Helper
    {

        /// <summary>
        /// base64编码的图片保存到本地，并且返回本地路径
        /// </summary>
        /// <param name="base64Str"></param>
        /// <returns></returns>
        public static string base64ToImages(string base64Str)
        {
            base64Str = base64Str.Substring(base64Str.IndexOf(";base64,")+8);
            string picPath = "";
            MemoryStream ms=null;
            Bitmap bmp=null;
            try
            {
                byte[] arr = Convert.FromBase64String(base64Str);
                ms = new MemoryStream(arr);
                bmp = new Bitmap(ms);
                string path = "/upload/wxapp/";
                string txtFileName = Guid.NewGuid().ToString();
                picPath = path + txtFileName + ".jpg";
                bmp.Save(Utils.GetMapPath(picPath), System.Drawing.Imaging.ImageFormat.Jpeg);
                //bmp.Save(txtFileName + ".bmp", ImageFormat.Bmp);
                //bmp.Save(txtFileName + ".gif", ImageFormat.Gif);
                //bmp.Save(txtFileName + ".png", ImageFormat.Png);


            }
            catch (Exception ex)
            {
                log.LogHelper.Error("生成图片报错："+ex.Message,ex);
            }
            finally
            {
                ms.Close();
                bmp.Dispose();
            }

          

            return picPath;

        }

        private void ImgToBase64String(string Imagefilename)
        {
            try
            {
                Bitmap bmp = new Bitmap(Imagefilename);
              
                FileStream fs = new FileStream(Imagefilename + ".txt", FileMode.Create);
                StreamWriter sw = new StreamWriter(fs);

                MemoryStream ms = new MemoryStream();
                bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                byte[] arr = new byte[ms.Length];
                ms.Position = 0;
                ms.Read(arr, 0, (int)ms.Length);
                ms.Close();
                String strbaser64 = Convert.ToBase64String(arr);
                sw.Write(strbaser64);

                sw.Close();
                fs.Close();
                // MessageBox.Show("转换成功!");
            }
            catch (Exception ex)
            {
               
            }
        }

    }
}
